package ink.feny.security.filter;

import cn.hutool.json.JSONUtil;
import ink.feny.security.property.JwtAuthProperty;
import ink.feny.security.service.JwtService;
import ink.feny.security.service.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Jwt Token过滤器，token校验
 * @author Feny
 * @date Created in 2021/4/28
 */
public class JwtTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtAuthProperty property;
    @Autowired
    private JwtService jwtService;
    @Autowired
    private UserAuthService authService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader(property.getHeader());
        if (Objects.nonNull(token)) {
            if (jwtService.validateToken(token)) {
                String subject = jwtService.getSubjectFromToken(token);
                UserDetails userDetails = authService.loadUserByUsername(subject);
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("msg", "无效 token");
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.getWriter().write(JSONUtil.toJsonPrettyStr(result));
                return;
            }
        }
        chain.doFilter(request, response);
    }
}
